package com.gzxw.mogublog.admin.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzxw.mogublog.commons.entity.Admin;
import com.gzxw.mogublog.commons.entity.Role;
import com.gzxw.mogublog.xo.mapper.AdminMapper;
import com.gzxw.mogublog.commons.config.security.LoginUser;
import com.gzxw.mogublog.xo.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) {

        LoginUser loginUser = null;
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name", username);
        queryWrapper.eq("status", "1");
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin == null) {
            // TODO 设置错误登录次数
            throw new RuntimeException("该管理员不存在");
        }

        //查询出角色信息封装到admin中
        Role role = roleService.getById(admin.getRoleUid());
        List<String> roleNames = Collections.singletonList(role.getRoleName());
        admin.setRoleNames(roleNames);
        loginUser = new LoginUser(admin);
        loginUser.setAuthorities(roleNames);

        return loginUser;
    }
}
